package com.grow.greenhouse.utils;

import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.BatchStatus;
import com.qiniu.util.Auth;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

@Component
public class QiNiuCloudUtil {

    //设置好账号的ACCESS_KEY和SECRET_KEY
    private static final String QiniuCloud_accessKey = "v8NzwalRLIQw8JZ4dM6NDgS_onxBf1jiKo7Rj0Jc";
    //这两个登录七牛 账号里面可以找到
    private static final String QiniuCloud_secretKey = "313oz0xzxZFy3g_JPZzT-vivQWyEQhTGfA5GiP0C";

    //要上传的空间
    private static final String QiniuCloud_bucket = "testand";
    //对应要上传到七牛上 你的那个路径（自己建文件夹 注意设置私有）

    //上传到七牛后保存的文件名
    private static final String customImageSuffix = ".png";//定义图片保存后的后缀
    private static final String customVideoSuffix = ".mp4";//定义图片保存后的后缀

    private static final String QiniuCloud_domainName ="http://qiniu.yyhui.top";

    //密钥配置
    Auth auth = Auth.create(QiniuCloud_accessKey, QiniuCloud_secretKey);

        /**
         * 上传图片到七牛云
         * @param file 图片
         * @return 返回图片存储后的新图片名
         * @throws Exception
         */
        public static Object QiniuCloudUploadImage(MultipartFile file) throws Exception{
            if(file.isEmpty()) {
                return "文件为空";
            }else if(file.getSize() > 1024*1024*10){
                return "文件大于10M";
            }
            //获取图片后缀
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            //允许上传的图片格式集合
            String[] suffixes = new String[]{".bmp", ".jpeg", ".jpg", ".png"};
            boolean bool = false;
            //判断格式是否在suffixes中
            for(String string : suffixes){
                if (string.equals(suffix)){
                    bool = true;
                    break;
                }
            }
            if(!bool){
                return "图片格式错误";
            }
            byte[] bytes = file.getBytes();
            String imageName = DigestUtils.md5DigestAsHex(bytes);//将图片md5的值作为图片名，避免重复图片浪费空间
            String key = imageName + customImageSuffix;//图片保存到七牛云后的文件名
            return upLoadFile(file,key);
        }
    /**
     * 上传视频到七牛云
     * @param file 视频
     * @return 返回视频存储后的新视频名
     * @throws Exception
     */
    public static Object QiniuCloudUploadVideo(MultipartFile file) throws Exception{
        if(file.isEmpty()) {
            return "文件为空";
        }
        //获取图片后缀
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //允许上传的图片格式集合
        String[] suffixes = new String[]{".mp4", ".avi", ".mov", ".wmv", ".flv", ".mkv",
                ".mpeg", ".mpg", ".rmvb", ".vob", ".webm"};
        boolean bool = false;
        //判断格式是否在suffixes中
        for(String string : suffixes){
            if (string.equals(suffix)){
                bool = true;
                break;
            }
        }
        if(!bool){
            return "视频格式错误";
        }
        byte[] bytes = file.getBytes();
        String videoName = DigestUtils.md5DigestAsHex(bytes);//将图片md5的值作为视频名，避免重复视频浪费空间
        String key = videoName + customVideoSuffix;//图片保存到七牛云后的视频名
        return upLoadFile(file,key);
    }
    private static String upLoadFile(MultipartFile file,String key) throws IOException {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;//指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        //生成上传凭证，然后准备上传
        String accessKey = QiniuCloud_accessKey;
        String secretKey = QiniuCloud_secretKey;
        String bucket = QiniuCloud_bucket;


        try {
            byte[] uploadBytes = file.getBytes();
            ByteArrayInputStream byteInputStream=new ByteArrayInputStream(uploadBytes);
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);

            try {
                uploadManager.put(byteInputStream,key,upToken,null, null);
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println("七牛云ERROR:" + r.toString());
                try {
                    System.err.println("七牛云ERROR:" + r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (UnsupportedEncodingException ex) {
            //ignore
        }

        return key;
    }


    /**
     * 获取文件链接
     * 获取七牛云图片链接
     * @param fileName 图片名
     * @return 返回图片链接
     */
    public static Object QiniuCloudDownloadImage(String fileName){
        String fileUrl = String.format("%s/%s", QiniuCloud_domainName, fileName);
        return fileUrl;
    }


    /**
     * 批量删除文件(可以只删除一个)
     * 从七牛云删除图片
     * @param fileNameList 图片名集合
     * @return 返回每张图片的删除结果
     */
    public static Object QiniuCloudDeleteImage(String[] fileNameList){
        //用Json格式传数组时直接传["xxx", "xxx", "xxx", "xxx"]
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.region0());
        //生成凭证
        String accessKey = QiniuCloud_accessKey;
        String secretKey = QiniuCloud_secretKey;
        String bucket = QiniuCloud_bucket;
        Auth auth = Auth.create(accessKey, secretKey);
        BucketManager bucketManager = new BucketManager(auth, cfg);
        //创建一个用来接收删除结果的集合
        List<String> list = new ArrayList<>();
        try {
            //单次批量请求的文件数量不得超过1000
            BucketManager.BatchOperations batchOperations = new BucketManager.BatchOperations();
            batchOperations.addDeleteOp(bucket, fileNameList);
            Response response = bucketManager.batch(batchOperations);
            BatchStatus[] batchStatusList = response.jsonToObject(BatchStatus[].class);
            for (int i = 0; i < fileNameList.length; i++) {
                BatchStatus status = batchStatusList[i];
                if (status.code == 200) {//成功返回文件名+true并添加进集合
                    list.add("{fileName:"+fileNameList[i]+",deleteResult:true}");
                }else {//失败返回文件名+false并添加进集合
                    list.add("{fileName:"+fileNameList[i]+",deleteResult:false}");
                }
            }
        } catch (QiniuException ex) {
            System.err.println("七牛云ERROR:" + ex.response.toString());
        }
        return list;
    }


}
